package com.ywgt.aba;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class ABAtest {
    public static void main(String[] args) {
        AtomicStampedReference<Integer> stampedReference=new AtomicStampedReference<Integer>(10,1);//加上时间戳的原子类，设置初始参数以及时间戳

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+stampedReference.getStamp());
            int stamp = stampedReference.getStamp();//获取线程开始前的时间戳，根据时间戳进行数据更新
            System.out.println(stampedReference.compareAndSet(10, 20, stamp, stampedReference.getStamp() + 1));
            System.out.println(Thread.currentThread().getName()+stampedReference.getStamp());
            System.out.println(stampedReference.compareAndSet(20, 10, stamp+1, stampedReference.getStamp() + 1));
            System.out.println(Thread.currentThread().getName()+stampedReference.getStamp());
            },"A").start();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+stampedReference.getStamp());
            int stamp = stampedReference.getStamp();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(stampedReference.compareAndSet(10, 20, stamp, stampedReference.getStamp() + 1));
            System.out.println(Thread.currentThread().getName()+stampedReference.getStamp());
        },"B").start();
    }
}
